package com.example.nio.nio;

import com.example.nio.nio.util.PacketWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.*;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @auther:lgb
 * @Date: 2021/5/3
 */
public class NIOTcpClient {
    private static final int PORT = 5555;
    private static final String IP_ADDRESS = "localhost";
    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);

        socketChannel.connect(new InetSocketAddress(IP_ADDRESS, PORT));
        while (!socketChannel.finishConnect()) {};

        new Thread(new SendRunnable(socketChannel)).start();

        System.out.println("Connecting to " + IP_ADDRESS + " on " + PORT);
        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    StringBuilder sb = new StringBuilder();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    while (channel.read(byteBuffer) > 0) {
                        byteBuffer.flip();
                        sb.append(new String(byteBuffer.array()));
                        byteBuffer.clear();
                    }
                    System.out.println("[server] " + sb.toString());
                }
                iterator.remove();
            }
        }
    }

    private static class SendRunnable implements Runnable {

        private SocketChannel socketChannel;
        public SendRunnable(SocketChannel socketChannel) {
            this.socketChannel = socketChannel;
        }

        @Override
        public void run() {
            System.out.println("Type to send message:");
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            try {
                socketChannel.socket().setSendBufferSize(102400);
            } catch (SocketException e) {
                e.printStackTrace();
            }
            int i = 0;
            while (i < 5) {
                try {
                    String msg = "客户端发送了第" + (i++) + "条消息";
                    // buffer.flip();
                    // buffer.compact(); // 要从读模式到写模式 使用compact()才有意义；
                    buffer.clear();
                    byte[] bytes = new PacketWrapper(msg).getBytes();
                    System.out.println(msg);
                    buffer.put(bytes);
                    // 变成读模式
                    buffer.flip();
                    while (buffer.hasRemaining()) {
                        //给服务写消息
                       socketChannel.write(buffer);


                    }
                    Thread.sleep(20);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
